package com.ruoyi.web.controller.system;

import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.*;
import com.ruoyi.system.domain.DeviceTerminal;
import com.ruoyi.system.domain.Lwm2mCredentials;
import com.ruoyi.system.domain.SysCompanyThingsboard;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/device.v2")
public class DeviceTerminalLwm2mController extends BaseController
{
    @Autowired
    private ISysCompanyThingsboardService sysCompanyThingsboardService;

    @Autowired
    IThingsBoardTenantService thingsBoardTenantService;

    @Autowired
    IProductService productService;

    @Autowired
    private IDeviceTerminalService deviceTerminalService;

    @Autowired
    private IDeviceTerminalLwm2mService deviceTerminalLwm2mService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;

    private AjaxResult checkExistance(Lwm2mCredentials lwm2mCredentials) {
        Map<String, Object> existance = deviceTerminalLwm2mService.findExistance(lwm2mCredentials);
        if (existance != null) {
            Object device_terminal_id_exists = existance.get("device_terminal_id_exists");
            if (device_terminal_id_exists != null && Integer.parseInt(device_terminal_id_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "产品终端id已经存在");
            }
            Object client_id_exists = existance.get("client_id_exists");
            if (client_id_exists != null && Integer.parseInt(client_id_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "客户端id已经存在");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:device:terminal:lwm2m:credentials:set')")
    @PostMapping(value = "/terminal/lwm2m/credentials", produces = "application/json;charset=UTF-8")
    @Log(title = "产品终端", businessType = BusinessType.INSERT)
    public AjaxResult addTerminalLwm2mCredentials(@RequestBody @Validated(Create.class) Lwm2mCredentials lwm2mCredentials) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysCompanyThingsboard sysCompanyThingsboard = sysCompanyThingsboardService.selectSysCompanyThingsboardByUser(loginUser.getUser());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        lwm2mCredentials.setCompanyId(companyId);
        AjaxResult ret = checkExistance(lwm2mCredentials);
        if (ret != null) {
            return ret;
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", lwm2mCredentials.getDeviceTerminalId());
        DeviceTerminal deviceTerminal = deviceTerminalService.retrieve(queryVo);
        if (deviceTerminal == null) {
            return AjaxResult.error("没有找到指定的产品终端");
        }
        projectAuthorizeService.checkProjectIsAuthorizeWithDeviceId(loginUser.getUser(),deviceTerminal.getDeviceId());
        if (!"LwM2M".equals(deviceTerminal.getProductTerminalProtocol())) {
            return AjaxResult.error("指定的产品终端不是LwM2M产品");
        }
        lwm2mCredentials.setTbDeviceId(deviceTerminal.getTbDeviceId());
        Integer id = deviceTerminalLwm2mService.createCredentials(lwm2mCredentials, sysCompanyThingsboard);
        if (id != null) {
            return AjaxResult.success(lwm2mCredentials);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:device:terminal:lwm2m:credentials:get')")
    @GetMapping(value = "/terminal/lwm2m/credentials/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieveTerminalLwm2mCredentials(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        Lwm2mCredentials lwm2mCredentials = deviceTerminalLwm2mService.retrieveCredentials(queryVo);
        if (lwm2mCredentials == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(lwm2mCredentials);
    }

    @PreAuthorize("@ss.hasPermi('system:device:terminal:lwm2m:credentials:set')")
    @PutMapping(value = "/terminal/lwm2m/credentials/edit", produces = "application/json;charset=UTF-8")
    @Log(title = "产品终端", businessType = BusinessType.UPDATE)
    public AjaxResult editTerminalLwm2mCredentials(@RequestBody @Validated(Update.class) Lwm2mCredentials lwm2mCredentials) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysCompanyThingsboard sysCompanyThingsboard = sysCompanyThingsboardService.selectSysCompanyThingsboardByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", lwm2mCredentials.getId());
        Lwm2mCredentials target = deviceTerminalLwm2mService.retrieveCredentials(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        lwm2mCredentials.setDeviceTerminalId(target.getDeviceTerminalId());
        lwm2mCredentials.setTbDeviceId(target.getTbDeviceId());
        AjaxResult ret = checkExistance(lwm2mCredentials);
        if (ret != null) {
            return ret;
        }
        if (deviceTerminalLwm2mService.updateCredentials(lwm2mCredentials, sysCompanyThingsboard)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
